package org.uu.mybatisplus.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.uu.mybatisplus.dao.UserDao;
import org.uu.mybatisplus.entity.UserDto;
import org.uu.mybatisplus.service.IUserService;
import org.uu.mybatisplus.utils.UuBeanUtils;

import javax.validation.Valid;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/user/save")
    public boolean save(@RequestBody @Valid UserDto userDTO) {
        UserDao userDAO = new UserDao();
        BeanUtils.copyProperties(userDTO, userDAO);
        return userService.saveUser(userDAO);
    }

    @RequestMapping(value = "/user/update", method = RequestMethod.POST)
    public boolean update(@RequestBody UserDto userDTO) {
        UserDao userDAO = new UserDao();
        BeanUtils.copyProperties(userDTO, userDAO);
        return userService.update(userDAO);
    }

    @GetMapping("/user/list")
    public List<UserDto> list() {
        List<UserDao> list = userService.getList();
        List<UserDto> userDtos = UuBeanUtils.copyBeanList(list, UserDto.class);
        return userDtos;
    }

    @RequestMapping(value = "/user/page", method = RequestMethod.GET)
    public Page page(@RequestParam int current, @RequestParam int size) {
        return userService.page(new Page<>(current, size), new QueryWrapper(new UserDao()));
    }

    @RequestMapping(value = "/user/delete/{id}", method = RequestMethod.DELETE)
    public boolean deleteById(@PathVariable("id") long id) {
        return userService.deleteById(id);
    }

    @GetMapping("/user/selectBynickname")
    public List<UserDao> selectByNickname(@RequestParam("nickName") String nickName) {
        return userService.selectByNickname(nickName);
    }
}
